var frameHeight = 0,frameHrefs = {},scale = window.screen.width/1536;;
$(function () {
    // config  1536  864
	
	

    getBussErrorData();
    frameHeight = $(document.body).height()-70-5;
    $('#context').height(frameHeight);


    $('#home').click(toHome);
    $('.nav .menu .home .title').click(toHome);

    $('.icon-exit').parent().click(logout);

    $('.top .links > li').click(function (e) {
        e.stopPropagation();
        var tg = $(this).attr('class');
        $('.fly[tg="'+tg+'"]').toggle();
    });

    $('#lockScreen').click(function () {
        $('div[tid="lockScreen"]').show();
    });
    
    $('#changePass').click(function () {
        app.window(layer,{
            title:'修改密码',
            area: ['400px', '260px'],
            maxmin:false,
            content: 'changepass.html'
        });

    });

});

function toHome() {
    hideTabs();
    $('#home').addClass('active');
    $('#context').show();
}

function addOrActTab(id,name,href) {
    hideTabs();

    if( $('#'+id).length > 0 ){
        activeTab(id,href);
        return;
    }

    $('.tabs .head').append('<a id="'+id+'" data-url="'+href+'" class="tab active">' +
        '<span>'+name+'</span>' +
        '<span class="iconfont icon-close-nal"></span>' +
        '</a>');

    $('#'+id+' .iconfont').mouseover(function () {
        $(this).removeClass("icon-close-nal").addClass("icon-close-hover");
    }).mouseout(function () {
        $(this).removeClass("icon-close-hover").addClass("icon-close-nal");
    }).click(function () {
        $('#'+id).remove();
        $('#frame'+id).remove();
        var lastId = $('.tabs .head .tab').last()[0].id;
        if( lastId == 'home' ){
            toHome();
        }else{
            activeTab(lastId);
        }
    });

    $('#'+id).click(function () {
        hideTabs();
        activeTab(id);
    });

    var hrefs = href.split('?');
    if( hrefs.length == 2 ){
        href = hrefs[0]+'.html?'+hrefs[1].replace('.html','');
    }
    $('.tabs .body').append('<iframe width="100%" height="'+frameHeight+'" src="/html/'+href+'" id="frame'+id+'" name="context" frameborder="0" scrolling="yes" marginheight="0" marginwidth="0"></iframe>');
}

function hideTabs() {
    $('.tabs .head .tab').removeClass('active');
    $('.tabs .body iframe').hide();
}

function activeTab(id,href) {
    $('#'+id).addClass('active');
    if(href){
        var hrefs = href.split('?');
        if( hrefs.length == 2 ){
            href = hrefs[0]+'.html?'+hrefs[1].replace('.html','');
        }
        $('#frame'+id).attr('src','/html/'+href);
    }
    $('#frame'+id).show();
}

function getElementPoint(ele) {
    var y = ele.offset().top;
    var x = ele.offset().left;
    return {x:x,y:y};
}

function activeMenuAction() {
    $('.menu .submenu > ul').each(function () {
        var height = $(this).height();
        var point = getElementPoint($(this).parent().find('.zk'));
        if( $(this).attr('type') == 'end' && $(window).height() < 663 ){
            point.y -= 100 - ($(window).height()-578);
        }
        $(this).css({"top":(point.y-height/2)+"px","left":(point.x+30)+"px"});
    });

    $('.menu .submenu').mouseover(function () {
        $(this).find('.im-font span').css({"color":"#fff"});
        $(this).find('>ul').show();
    }).mouseout(function () {
        $(this).find('.im-font span').css({"color":"#cdf4f0"});
        $(this).find('>ul').hide();
    });

    $('.menu .submenu > ul > li > ul > li').mouseover(function () {
        $(this).css({"color":"#fff"});
    }).mouseout(function () {
        $(this).css({"color":"#cdf4f0"});
    });

    $('.menu .submenu > ul > li > ul > li').click(function () {
        var menu = $(this).data();
        menuClick({id:menu.id,name:menu.name,href:menu.href+".html",_this:$(this)});
    });
}

function menuClick(o) {
    if( o.id == 731 ){
        layer.confirm('<span style="font-weight:700;">成本重算后商品的成本可能会发生变化，请确认！</span><br><input type="checkbox"/><span>我已清楚了解将产生的后果</span>', {icon: 3, title:'提示'}, function(index){
            return;
            layer.close(index);
        });
    }else if( o.id == 732 ){
        layer.confirm('<span style="font-weight:700;">重新初始化数据后会清空所有数据，请确认！</span><br><input a="10023001" type="checkbox"/><span>我已清楚了解将产生的后果</span><br><input a="10023002" type="checkbox"/><span>我已知道现有的所有数据都会清空</span>', {icon: 3, title:'提示'}, function(index){
            var c1 = $('input[a="10023001"]').prop('checked');
            var c2 = $('input[a="10023002"]').prop('checked');
            if( c1 && c2 ){
                layer.load(1, {shade: [0.3,'#fff']});
                app.request({
                    url:'schema/init',
                    success:function(resp){
                        location.href = "http://192.168.50.101";
                    }
                });
                layer.close(index);
            }else{
                app.message(layer,'请勾选我已知晓');
            }
        });
    }else{
        if( !o._this ) o._this = $('li[tid="submenu'+o.id+'"]');
        addOrActTab('c'+o.id,o.name,o.href);
        o._this.parent().parent().parent().hide();
    }
    
}

function initMenus() {
    app.request({
        url:'user/findMenus',
        success:function(resp){
            if( resp.result==0 ){
                createMenus(resp.data);
            }else {
                //location.href = "./login.html";
            }
        }
    });
}

function getBussErrorData() {
    app.request({
        url:'bussError',
        data:{_abc:new Date().getTime()},
        success:function(resp){
            if( resp.result==2 ){
                location.href = "./login.html";
            }else {

                $('#company_name').html(resp.loginCompanyName);
                
                top.customerId = resp.customerId;
                top.loginCompanyId = resp.loginCompanyId;
                top.loginCompanyLogicalCode = resp.loginCompanyLogicalCode;
                top.loginUserId = resp.loginUserId;
                top.loginName = resp.loginName;
                top.loginCompanyName = resp.loginCompanyName;
                
                top.serverTime = parseInt(resp.serverTime);
                top.clientTime = new Date().getTime();
                top.bussError = resp.bussError;
                top.dicts = resp.dicts;
                
                initMenus();
                
                $('#context').attr('src','/html/index_report.html');
            }
        }
    });
}

function createMenus(menus) {
    for( var i=0 ; i<menus.length ; i++ ){
        var menu = menus[i];
        if( menu.parentId == -1 ){
            if( menu.id < 5 ){
                $('.menu .header[type="base"]').before(assembleSubmenu(menus,menu,'base'));
            }else{
                $('.menu li[type="end"]').before(assembleSubmenu(menus,menu,'end'));
            }
        }
    }
    activeMenuAction();
    initPageSize();
}

function initPageSize() {
    if( $(window).height() < 622 ){
        $('.nav .menu > li').css({"padding":"7px"});
    }
	$('.nav .submenu .title').css({"font-size":scale*12+"px"});
}

function assembleSubmenu(menus,menu,type) {
    var ul = $('<ul type="'+type+'"></ul>');
    var li1 = $('<li style="float: left;"></li>');
    var ul1 = $('<ul></ul>');
    var li2 = $('<li style="float: left;"></li>');
    var ul2 = $('<ul></ul>');

    for( var i=0 ; i<menus.length ; i++ ){
        var m = menus[i];
        if( m.parentId == menu.id ){
            var xli = $('<li tid="submenu'+m.id+'">'+m.name+'</li>');
            xli.data(m);
            if( m.id % 100 < 30 ){
                ul1.append(xli);
            }else{
                ul2.append(xli);
            }
        }
    }

    li1.append(ul1);
    li2.append(ul2);
    ul.append(li1);
    ul.append(li2);

    return $('<li class="submenu">' +
        '<a class="im-font">' +
        '<span class="iconfont icon-'+menu.icon+'"></span>' +
        '<span class="title">'+menu.name+'</span>' +
        '<span class="iconfont icon-zk zk"></span>' +
        '</a></li>').append(ul);
}

function logout() {
    app.request({
        url:'logout',
        success:function(resp){
            if( resp.result==0 ){
                $.cookie('token','1', { expires: 7, path: '/' });
                $.cookie('login','2', { expires: 7, path: '/' });
                location.href = "login.html";
            }
        }
    });
}